package com.garry.common.security.util;

import com.garry.user.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;

/**
 * Created by GarryGe on 2016/12/11.
 */
public class PasswordUtil {

    private static RandomNumberGenerator generator=new SecureRandomNumberGenerator();

    private static String algorithmName = "md5";

    public static int hashIterations = 1024;
    /**
     * 根据salt和密码进行md5加密,times在改项目中为2
     * @return
     */
    public static String encrypt(String password,String salt,int times){
        return new Md5Hash(password,salt,times).toString();
    }

    public static void encrypt(User user){
        user.setSalt(generator.nextBytes().toHex());

        String newPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }
 }
